<template>
  <div class="song-container">

    <!-- 歌曲详情区域 -->
    <div class="song-detail-container">
      <!-- 左侧：专辑封面 -->
      <div class="album-cover-wrapper">
        <img
          :src="currentSong?.picUrl || songDefaultImage"
          alt="专辑封面"
          class="album-cover"
          :class="{ rotating: isPlaying }"
        />

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" round @click="downloadSong">
            下载这首歌
          </el-button>
        </div>
      </div>

      <!-- 右侧：歌曲信息 & 歌词 -->
      <div class="song-info-wrapper">
        <!-- 基本信息 -->
        <!-- 页面标题 -->
        <div class="page-header">
          <h2>{{ currentSong?.name }} - {{ currentSong?.singerName }}</h2>
        </div>

        <div class="basic-info">
          <div class="info-row">
            <span>专辑：</span>
            <span>{{ currentSong?.album || '未知专辑' }}</span>
          </div>
          <div class="info-row">
            <span>歌手：</span>
            <span>{{ currentSong?.singerName }}</span>
          </div>
        </div>

        <!-- 歌词区域 -->
        <div class="lyrics-container">
          <div class="lyrics-content" ref="lyricsContainer">
            <div
              v-for="(line, index) in lyrics"
              :key="index"
              class="lyric-line"
              :class="{ active: index === currentLyricIndex }"
            >
              {{ line.text }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import defaultImage from '@/assets/img/song-default.png'
import { usePlayerStore } from '@/store/player'
import { useRouter } from 'vue-router'

export default {
  name: 'SongPage',
  setup() {
    const router = useRouter()
    const playerStore = usePlayerStore()

    const songDefaultImage = defaultImage

    // 当前歌曲数据
    const currentSong = ref(null)
    
    // 当前播放时间
    const currentTime = ref(0)

    // 歌词容器
    const lyricsContainer = ref(null)
    // 歌词数据
    const lyrics = ref([])
    // 当前歌词索引
    const currentLyricIndex = ref(-1)

    const isPlaying = ref(false)

    // 获取当前播放歌曲
    const getCurrentSong = () => {
      const song = playerStore.getCurrentSong
      if (song && song.id) {
        currentSong.value = song
      }
    }

    /**
     * 解析歌词
     * @param {string} lyricText - 歌词文本
     * @returns {Array} 解析后的歌词数组
     */
    const parseLyrics = (lyricText) => {
      if (!lyricText || typeof lyricText !== 'string') {
        console.log('Invalid lyric text:', lyricText)
        return []
      }

      console.log('Parsing lyrics:', lyricText)

      const lines = lyricText.split('\n')
      const parsedLyrics = []

      for (const line of lines) {
        // 跳过空行
        if (!line.trim()) continue

        // 匹配时间戳格式 [mm:ss.xx] 或 [mm:ss]
        const timeMatches = [...line.matchAll(/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/g)]

        // 提取歌词文本（去掉所有时间戳）
        const text = line.replace(/\[\d{2}:\d{2}(?:\.\d{2,3})?\]/g, '').trim()

        // 如果没有文本内容，跳过这一行
        if (!text) continue

        // 处理可能包含多个时间戳的行（如歌词重复）
        if (timeMatches.length > 0) {
          for (const match of timeMatches) {
            const minutes = parseInt(match[1])
            const seconds = parseInt(match[2])
            // 处理毫秒部分，确保是正确的数值
            const milliseconds = match[3] ? parseInt(match[3].padEnd(3, '0').substring(0, 3)) : 0
            const time = minutes * 60 + seconds + milliseconds / 1000

            parsedLyrics.push({
              time: time,
              text: text
            })
          }
        } else {
          // 如果没有时间戳但有文本内容（如歌词信息行），添加一个特殊时间
          parsedLyrics.push({
            time: 0,
            text: text
          })
        }
      }

      // 按时间排序
      parsedLyrics.sort((a, b) => a.time - b.time)

      console.log("Parsed lyrics:", parsedLyrics)
      return parsedLyrics
    }

    /**
     * 更新当前歌词索引
     */
    const updateCurrentLyric = () => {
      if (lyrics.value.length === 0) return

      // 查找当前时间对应的歌词
      let newIndex = -1
      for (let i = 0; i < lyrics.value.length; i++) {
        // 如果是最后一行歌词，或者下一歌词的时间大于当前时间
        if (i === lyrics.value.length - 1 || lyrics.value[i + 1].time > currentTime.value) {
          newIndex = i
          break
        }
      }

      // 只有在索引改变时才更新
      if (currentLyricIndex.value !== newIndex) {
        currentLyricIndex.value = newIndex
        // 滚动到当前歌词
        scrollToCurrentLyric()
      }
    }

    /**
     * 滚动到当前歌词
     */
    const scrollToCurrentLyric = () => {
      nextTick(() => {
        if (lyricsContainer.value && currentLyricIndex.value >= 0) {
          const lyricLines = lyricsContainer.value.querySelectorAll('.lyric-line')
          if (lyricLines[currentLyricIndex.value]) {
            lyricLines[currentLyricIndex.value].scrollIntoView({
              behavior: 'smooth',
              block: 'center'
            })
          }
        }
      })
    }

    // 监听播放状态变化
    watch(
      () => playerStore.isPlaying,
      (newVal) => {
        isPlaying.value = newVal
      },
      { immediate: true }
    )

    // 监听当前歌曲变化
    watch(
      () => playerStore.getCurrentSong,
      (newSong) => {
        if (newSong && newSong.id) {
          currentSong.value = newSong
          
          // 解析歌词
          let lyricText = ''
          // 检查多个可能的歌词字段
          if (newSong.songLyr) {
            lyricText = newSong.songLyr
          } else if (newSong.lyrics) {
            lyricText = newSong.lyrics
          }

          console.log('Lyric text to parse:', lyricText)

          if (lyricText && typeof lyricText === 'string' && lyricText.trim()) {
            lyrics.value = parseLyrics(lyricText)
            console.log('Parsed lyrics:', lyrics.value)
          } else {
            lyrics.value = []
          }
          currentLyricIndex.value = -1
        }
      },
      { immediate: true, deep: true }
    )

    // 监听播放时间变化
    watch(
      () => playerStore.getCurrentTime,
      (newTime) => {
        currentTime.value = newTime
        updateCurrentLyric()
      },
      { immediate: true }
    )

    // 下载歌曲
    const downloadSong = () => {
      if (!currentSong.value?.url) {
        ElMessage.warning('暂无下载链接')
        return
      }
      window.open(currentSong.value.url, '_blank')
    }

    // 初始化
    onMounted(() => {
      getCurrentSong()
    })

    return {
      currentSong,
      lyrics,
      currentLyricIndex,
      isPlaying,
      songDefaultImage,
      lyricsContainer,
      downloadSong
    }
  }
}
</script>

<style scoped>
.song-container {
  padding: 20px;
  width: 1200px;
  margin: 0 auto;
}

.song-detail-container {
  display: flex;
  gap: 60px;
  align-items: flex-start;
  margin-top: 20px;
}

/* 左侧专辑封面区域 */
.album-cover-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.album-cover {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s ease;
}

.album-cover.rotating {
  animation: rotate 10s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 右侧歌曲信息区域 */
.song-info-wrapper {
  flex: 1;
  min-width: 0;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

/* 基本信息行 - 专辑和歌手在同一行 */
.basic-info {
  display: flex;
  gap: 40px;
  margin-bottom: 30px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.info-row {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.info-row span:first-child {
  font-weight: 500;
  color: #333;
  margin-right: 8px;
}

/* 歌手名字加粗 */
.info-row:last-child span:last-child {
  font-weight: bold;
}

/* 歌词区域 */
.lyrics-container {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 12px;
  margin-bottom: 20px;
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e9ecef;
}

.lyrics-content {
  line-height: 2;
  font-size: 16px;
  color: #333;
  text-align: left;
}

.lyric-line {
  opacity: 0.7;
  transition: all 0.3s;
  padding: 2px 0;
}

.lyric-line.active {
  color: #1890ff;
  font-weight: 500;
  opacity: 1;
  transform: scale(1.02);
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 500;
}
</style>